package com.heixiu.gallery2

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.findNavController
import androidx.paging.PagedListAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.android.synthetic.main.gallery_item.view.*
import kotlinx.android.synthetic.main.gallery_load_more.view.*

class GalleryAdapter(val galleryViewModel: GalleryViewModel) :
    PagedListAdapter<PhotoItem, RecyclerView.ViewHolder>(DIFFCALLBACK) {

    private var isShowLoadMore = false
    private var networkStatus: NetworkStatus? = null

    init {
        galleryViewModel.retry()
    }

    fun updateNetworkStatus(networkStatus: NetworkStatus) {
        this.networkStatus = networkStatus
        when (networkStatus) {
            NetworkStatus.INITIAL_LOADING -> hideLoadMore()
            else -> showLoadMore()
        }
    }

    private fun hideLoadMore() {
        if (isShowLoadMore) {
            notifyItemRemoved(itemCount - 1)
        }
        isShowLoadMore = false
    }

    private fun showLoadMore() {
        if (isShowLoadMore) {
            notifyItemChanged(itemCount - 1)
        } else {
            isShowLoadMore = true
            notifyItemInserted(itemCount - 1)
        }
    }

    object DIFFCALLBACK : DiffUtil.ItemCallback<PhotoItem>() {
        override fun areItemsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: PhotoItem, newItem: PhotoItem): Boolean {
            return oldItem == newItem
        }
    }

    override fun getItemCount(): Int {
        return super.getItemCount() + if (isShowLoadMore) 1 else 0
    }

    override fun getItemViewType(position: Int): Int {
        return if (isShowLoadMore && position == itemCount - 1) R.layout.gallery_load_more else R.layout.gallery_item
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            R.layout.gallery_item -> GalleryViewHolder.newInstance(parent).also { holder ->
                holder.itemView.setOnClickListener {
                    Bundle().apply {
                        putInt("current_position", holder.bindingAdapterPosition)
                        val navController = it.findNavController()
                        navController.navigate(R.id.gallery_to_photos, this)
                    }
                }
            }
            else -> GalleryLoadMoreHoler.newInstance(parent).also { holder ->
                holder.itemView.let {
                    (it.layoutParams as StaggeredGridLayoutManager.LayoutParams).isFullSpan = true

                    it.setOnClickListener {
                        it.progressBarGalleryLoadMore.visibility = View.VISIBLE
                        it.textViewGalleryLoadMore.text = "正在加载"
                        it.textViewGalleryLoadMore.visibility = View.VISIBLE
                        galleryViewModel.retry()
                    }
                }
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder.itemViewType) {
            R.layout.gallery_item -> {
                val photoItem: PhotoItem = getItem(position) ?: return
                (holder as GalleryViewHolder).bindView(photoItem)
            }
            else -> {
                networkStatus?.let {
                    (holder as GalleryLoadMoreHoler).bindView(it)
                }
            }
        }
    }

}

class GalleryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

    companion object {
        fun newInstance(parent: ViewGroup): GalleryViewHolder {
            val view =
                LayoutInflater.from(parent.context).inflate(R.layout.gallery_item, parent, false)
            return GalleryViewHolder(view)
        }
    }

    fun bindView(photoItem: PhotoItem) {
        with(itemView) {
            shimmerLayout.apply {
                setShimmerColor(0x55ffffff)
                setShimmerAngle(0)
                startShimmerAnimation()
            }
            textViewUser.text = photoItem.user
            textViewLikes.text = photoItem.likes.toString()
            textViewFavorites.text = photoItem.favorites.toString()
            imageView.layoutParams.height = photoItem.photoHeight
        }

        Glide.with(itemView)
            .load(photoItem.smallPhoto)
            .placeholder(R.drawable.ic_photo_black_24dp)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false.also { itemView.shimmerLayout?.stopShimmerAnimation() }
                }

            })
            .into(itemView.imageView)
    }

}

class GalleryLoadMoreHoler(itemView: View) : RecyclerView.ViewHolder(itemView) {

    companion object {
        fun newInstance(parent: ViewGroup): GalleryLoadMoreHoler {
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.gallery_load_more, parent, false)
            return GalleryLoadMoreHoler(view)
        }
    }

    fun bindView(networkStatus: NetworkStatus) {
        with(itemView) {
            when (networkStatus) {
                com.heixiu.gallery2.NetworkStatus.LOADING -> {
                    isClickable = false
                    progressBarGalleryLoadMore.visibility = android.view.View.VISIBLE
                    textViewGalleryLoadMore.text = "图片加载中"
                    textViewGalleryLoadMore.visibility = android.view.View.VISIBLE
                }
                com.heixiu.gallery2.NetworkStatus.COMPLETED -> {
                    isClickable = false
                    progressBarGalleryLoadMore.visibility = android.view.View.GONE
                    textViewGalleryLoadMore.text = "没有更多图片了"
                    textViewGalleryLoadMore.visibility = android.view.View.VISIBLE
                }
                com.heixiu.gallery2.NetworkStatus.FAILED -> {
                    isClickable = true
                    progressBarGalleryLoadMore.visibility = android.view.View.GONE
                    textViewGalleryLoadMore.text = "网络故障，点击重试"
                    textViewGalleryLoadMore.visibility = android.view.View.VISIBLE
                }
                else -> {}
            }
        }
    }

}